<template>
  <div class="body">
    <basic-container>
      <div class="query_select">
        <!--筛选条件-->
        <cs-filter-query ref="csFilterQueryRef" :options="filterQueryOptions"
                         @change="handleChangeFilter"></cs-filter-query>

      </div>
      <div style="margin: 0 40px">
        <el-button size="mini" type="primary" @click="addTransfer">批量充值需求</el-button>
      </div>

      <el-drawer
        title='批量充值需求'
        size="80%"
        :visible.sync="addDrawerSwitch"
        :modal-append-to-body="false"
        :close-on-click-modal="false"
        :append-to-body="true"
        :wrapperClosable="false"
        @close="closeMoneyForm"
      >
        <el-divider></el-divider>
        <cs-drawer-container>
          <div class="add-money-box">
<!--            <el-form ref="kpiForm" label-position="top" :model="moneyForm" label-width="80px">-->
<!--              <el-form-item>-->
                <el-table
                  :data="moneyForm.request"
                  style="width: 100%"
                  ref="moneyTable"
                >
                  <el-table-column
                    prop="platformId"
                    :show-overflow-tooltip="true"
                    width="200"
                    label="账户ID">
<!--                    <template v-slot="{row, column, $index}">-->
<!--                      <el-select :ref="'accountId'+$index" v-if="row.accountIdSelectVisible" size="mini"-->
<!--                                 v-model="row.platformId" placeholder="请选择" filterable-->
<!--                                 @change="filterAccountsInfo($event,row)" @blur="handleBlurSelect($index,'accountId')">-->
<!--                        <el-option-->
<!--                          v-for="item in selectAccountList"-->
<!--                          :key="item.id"-->
<!--                          :label="item.platformId+'->'+item.name"-->
<!--                          :value="item.platformId">-->
<!--                        </el-option>-->
<!--                      </el-select>-->
<!--                      <el-button v-else :type="row.platformId?'primary':'warning'" size="mini" plain-->
<!--                                 @click="showEditItem($index,'accountId')">-->
<!--                        {{ row.platformId !== '' ? row.platformId : '请选择账户ID' }}-->
<!--                      </el-button>-->
<!--                    </template>-->
                  </el-table-column>
                  <el-table-column
                    prop="name"
                    :show-overflow-tooltip="true"
                    label="账户名称">
                  </el-table-column>
                  <el-table-column
                    prop="customerFullName"
                    :show-overflow-tooltip="true"
                    label="客户名称">
                    <template v-slot="{row}">
                      {{getCunstomerFullName(row.platformId)}}
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="platform"
                    label="媒体">
                  </el-table-column>
                  <el-table-column
                    prop="operatorName"
                    label="账户运营人">
                  </el-table-column>
                  <el-table-column
                    prop="limits"
                    label="账户余额">
                  </el-table-column>
                  <el-table-column
                    prop="amount"
                    label="充值金额">
                    <template v-slot="{row}">
                      <el-input size="mini" oninput="if(value<0)value=0"
                                v-model="row.amount" type="number"></el-input>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="level"
                    label="优先级"
                    :formatter="formatterLevel"
                    >
                    <template v-slot="{row}" >
                      <el-select size="mini" v-model="row.level" placeholder="请选择" filterable @change="()=>{$forceUpdate()}">
                        <el-option
                          v-for="item in levelList"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value">
                        </el-option>
                      </el-select>
                    </template>
                  </el-table-column>
                </el-table>
<!--                <el-link type="primary" @click="addMoneyCheck">+ 新增充值账户</el-link>-->
<!--              </el-form-item>-->
<!--            </el-form>-->
          </div>
          <template v-slot:bottom>
            <el-button  type="primary" size="mini" @click="saveRequest">保存</el-button>
            <el-button size="mini" @click="addDrawerSwitch = false">取消</el-button>
          </template>
        </cs-drawer-container>
      </el-drawer>

      <avue-crud :option="option"
                 :table-loading="loading"
                 :data="data"
                 :view-name="'account'"
                 :page.sync="page"
                 :row-class-name-rollback="getRowClassName"
                 ref="crud"
                 @sort-change="handleSortChange"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @refresh-change="refreshChange"
                 @selection-change="selectionChange"
                 @on-load="onLoad(page)">
        <template slot="menuRight" slot-scope="{size}">
          <span class="update_time">
          当前数据更新时间: {{ updateTime }}
        </span>
          <el-tooltip v-if="false" effect="dark" content="清空" placement="top">
            <el-button icon="el-icon-delete" size="small" circle @click="$refs.csFilterQueryRef.clear()"></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" content="导出" placement="top">
            <el-button icon="el-icon-download" size="small" circle @click="excelExport"></el-button>
          </el-tooltip>
        </template>

        <template slot="limitsHeader" slot-scope="{column}">
          <el-popover
            placement="bottom-start"
            width="200"
            trigger="hover"
          >
            <div class="popover_pane">
              <div>
                <i class="el-icon-info" style="color: #00a2ff"></i>
                <strong> 账户余额</strong>
              </div>
              <span>
                账户余额非实时更新，每日8:30、13:30、18:30更新<br>
                为方便计算，beetles系统将账户余额统一换算美元显示
              </span>
            </div>
            <span slot="reference" class="text-link">{{ (column || {}).label }}</span>
          </el-popover>
        </template>
        <template slot="threeDaysPredictCostHeader" slot-scope="{column}">
          <span slot="reference" class="text-link">{{ (column || {}).label }}</span>
        </template>
        <template slot="sevenDaysPredictCostHeader" slot-scope="{column}">
          <span slot="reference" class="text-link">{{ (column || {}).label }}</span>
        </template>
        <template slot-scope="{row}" slot="platform">
          <div style="display: flex; flex-wrap: wrap;">
            <div style="width: 20px;margin-right: 4px"
                 v-for="(item) in platformLogo(row.platform)">
              <img style="width: 100%" :src="item.url" :title="item.name">
            </div>
          </div>
        </template>
        <template slot-scope="{ row }" slot="limits">
          {{ thousandSeparator(row.limits) }}
        </template>
        <template slot-scope="{ row }" slot="threeDaysPredictCost">
          <el-popover
            placement="bottom-start"
            width="200"
            trigger="hover"
            v-if="row.threeDaysPredictCost*1>row.limits*1"
          >
            <div class="popover_pane">
              <div>
                <i class="el-icon-info" style="color: #00a2ff"></i>
                <strong> 3日告警</strong>
              </div>
              <span>
                当前账户的余额，预估在3日内消耗完
              </span>
            </div>
            <span slot="reference" class="text-link" style="color: red">{{
                thousandSeparator(row.threeDaysPredictCost)
              }}</span>
          </el-popover>
          <div v-else>
            {{ thousandSeparator(row.threeDaysPredictCost) }}
          </div>
        </template>
        <template slot-scope="{ row }" slot="sevenDaysPredictCost">
          <el-popover
            placement="bottom-start"
            width="200"
            trigger="hover"
            v-if="row.sevenDaysPredictCost*1>row.limits*1"
          >
            <div class="popover_pane">
              <div>
                <i class="el-icon-info" style="color: #00a2ff"></i>
                <strong> 7日告警</strong>
              </div>
              <span>
                当前账户的余额，预估在7日内消耗完
              </span>
            </div>
            <span slot="reference" class="text-link" style="color: red">{{
                thousandSeparator(row.sevenDaysPredictCost)
              }}</span>
          </el-popover>
          <div v-else>
            {{ thousandSeparator(row.sevenDaysPredictCost) }}
          </div>
        </template>
      </avue-crud>
    </basic-container>

  </div>
</template>

<script>
import {mapGetters} from "vuex";
import {getUrlData, getSysDictList} from '@/api/system/dict';
import CsFilterQuery from "@/components/CsFilterQuery/CsFilterQuery";
import {
  getList, excelExport,
} from "@/api/business/toolKitApi";
import {deepClone, findObjectList} from '@/util/util';
import {
  getOffer, getOperator
} from "@/api/dataReport/cost-report-new";
import {platformLogo} from '@/util/beetles';
import {thousandSeparator} from '@/util/util'
import {checkAuditTime, dateFormat} from '@/util/date'
import {getSelectAccountforTT,getSelectAccountfor, getTTAccountBalance, saveRequirementByBatch} from "@/api/accountOrTransfer/transfer";
import _ from "lodash";
import CsDrawerContainer from "@/components/CsDrawerContainer/CsDrawerContainer";
import {getCustomerList} from "@/api/finance/commonApi";

export default {
  components: {
    CsFilterQuery,
    CsDrawerContainer,
  },
  data() {
    return {
      query: {},
      updateTime: '2022-8-18 08:00:00',
      loading: true,
      selectionList:[],
      addDrawerSwitch:false,
      moneyForm: {
        request: []
      },
      platformIdList:[
        {platformId:'7171416320787939330'},
        {platformId:'7171416254744494082'},
        ],
      excludeSelection: [],
      selectAccountList: [],
      levelList: [
        {label: '马上', value: 2},
        {label: '当天', value: 1},
        {label: '一般', value: 0},
      ],
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      offerList: [],
      platformList: [],
      operatorList: [],
      customerList:[],
      alarmTimeList: [
        {label: '3日告警', value: '3'},
        {label: '7日告警', value: '7'},
      ],
      option: {
        // height:'55vh',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        menuWidth: 120,
        menu: false,
        addBtn: false,
        selection: true,
        dialogClickModal: false,
        dialogWidth: 1200,
        column: [
          {
            label: "账户名",
            prop: "name",
            overHidden: true,
            addDisplay: false,
            editDisplay: true,
            viewDisplay: true,
          },
          {
            label: "账户ID",
            prop: "platformId",
            overHidden: true,
            addDisplay: false,
            editDisplay: true,
            viewDisplay: true,
          }, {
            label: "账户运营人",
            prop: "operator",
            type: 'select',
            dicData: [],
            props: {
              label: "realName",
              value: "id"
            },
            viewDisplay: true,
            searchLabelWidth: 100,
            overHidden: true,
          },
          {
            label: "账户货币",
            prop: "currency",
            overHidden: true,
            hide: true,
            viewDisplay: true,
          },
          {
            label: "账户时区",
            prop: "timezone",
            overHidden: true,
            hide: true,
            viewDisplay: true,
          },
          {
            label: "订单名",
            prop: "offerName",
            type: 'select',
            viewDisplay: true,
            overHidden: true,
          },
          {
            label: "媒体",
            prop: "platform",
            type: 'select',
            dicData: [],
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            formsolt: true,
            overHidden: true,
          },
          {
            label: "账户余额USD",
            prop: "limits",
            addDisplay: false,
            editDisplay: false,
            overHidden: true,
            sortable: 'custom',
          },
          {
            label: "3日预估花费",
            prop: "threeDaysPredictCost",
            addDisplay: false,
            editDisplay: false,
            overHidden: true,
            sortable: 'custom',
          },
          {
            label: "7日预估花费",
            prop: "sevenDaysPredictCost",
            addDisplay: false,
            editDisplay: false,
            overHidden: true,
            sortable: 'custom',
          },
        ]
      },
      data: [],
      operatorId: [],
      // 排序
      sortList: [],
    };
  },
  computed: {
    ...mapGetters(["permission", "userInfo", "roles"]),
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
    // 媒体列表
    translatePlatformList() {
      return this.platformList.map(item => {
        return {
          label: item.dictValue,
          value: item.dictKey
        }
      })
    },
    // 筛选组件配置
    filterQueryOptions() {
      return [
        {
          value: 'name',
          label: '账户名',
        },
        {
          value: 'platformId',
          label: '账户ID',
        },
        {
          value: 'operatorName',
          label: '账户运营人',
          queryList: this.operatorList
        },
        {
          value: 'offerName',
          label: '订单名称',
          queryList: this.offerList
        }, {
          value: 'platform',
          label: '媒体',
          children: this.translatePlatformList
        }, {
          value: 'alarmTimeList',
          label: '告警时间',
          children: this.alarmTimeList
        },]
    },
  },
  created() {
    getSysDictList('platforms').then(map => {
      this.platformList = map['platforms'];
      findObjectList(this.option.column, 'platform', 'prop')[0].dicData = map['platforms'];
    });
    getUrlData('/api/blade-user/select/user').then(res => {
      findObjectList(this.option.column, 'operator', 'prop')[0].dicData = res.data.data;
    });
    this.getOfferList()
    this.getOperatorList();
  },
  mounted() {
    this.$nextTick(() => {
      this.setUpdateTime();
    })
  },
  methods: {
    // 筛选框查询
    handleChangeFilter(val) {
      this.query = val
      this.page.currentPage = 1;
      this.onLoad(this.page)
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page);
    },
    selectionChange(list){
      this.selectionList = list
      console.log(this.selectionList)
    },
    async getSelectAccountList() {
      const {data: res} = await getSelectAccountfor()
      this.selectAccountList = res.data
      // this.selectAccountListFixed = res.data
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getList(page.currentPage, page.pageSize, {
        sortList: JSON.stringify(this.sortList),
      },this.query).then(res => {
        const data = res.data.data;
        data.records.map((row, index) => {
          this.operatorId[index] = row.operator
        })
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
      });
    },
    addTransfer(){
      if (this.selectionList.length===0){
        this.$message.warning('请至少勾选一条数据！')
        return
      }
      getSelectAccountfor().then(res => {
        // console.log('res',res.data.data)
        this.customerList = res.data.data
        // console.log('qqq',this.customerList)
      })
      this.getSelectAccountList()
      this.addDrawerSwitch = true

      this.moneyForm.request = deepClone(this.selectionList)
      this.moneyForm.request.forEach((value,index)=>{
        // value['level'] = 0
        this.$set(value,"level",0)
      })

    },
    closeMoneyForm(){
      this.moneyForm.request = []
      this.excludeSelection = []
      this.selectAccountList = this.selectAccountListFixed
      this.addDrawerSwitch = false
    },
    getCunstomerFullName(val){
     return this.customerList.find(item=>item.platformId===val)['customerFullName']
    },
    // 获取账户名称
    async filterAccountsInfo(event, row) {
      const account = this.selectAccountList.find(item => item.platformId === event)
      this.excludeSelection.push(row.platformId)
      this.selectAccountList = this.selectAccountListFixed
        .filter(item =>  !this.excludeSelection.includes(item.platformId))
      const {data: {data}} = await getTTAccountBalance(row.platformId)
      row.accountName = account.name
      row.customerFullName = account.customerFullName
      row.platform = account.platform
      row.accountOperator = account.operatorName
      row.limits = data
    },
    // 选择器失去焦点事件
    handleBlurSelect(index, type) {
      setTimeout(() => {
        switch (type) {
          case 'accountId':
            this.moneyForm.request[index].accountIdSelectVisible = false
            break;
          case 'requirementName':
            this.moneyForm.request[index].requirementNameSelectVisible = false
            break;
        }
      }, 500)
    },
    // 展示选择修改框
    showEditItem(index, type) {
      switch (type) {
        case 'accountId':
          this.moneyForm.request[index].accountIdSelectVisible = true
          this.$nextTick(() => {
            this.$refs['accountId' + index].toggleMenu()
            this.$refs['accountId' + index].focus()
          })
          break;
        case 'requirementName':
          this.moneyForm.request[index].requirementNameSelectVisible = true
          this.$nextTick(() => {
            this.$refs['requirementName' + index].toggleMenu()
            this.$refs['requirementName' + index].focus()
          })
          break;
      }
    },
    // 有优先级
    formatterLevel(row, column, cellValue, index) {
      const temp = this.levelList.find(item => item.value === cellValue)
      if (temp === undefined) {
        return ''
      } else {
        return temp.label
      }
    },
    // 添加指标
    addMoneyCheck() {
      this.moneyForm.request.push({
        platformId: '',
        accountName: '',
        customerFullName: '',
        platform: '',
        accountOperator: '',
        amount: '',
        level: 0,
        requirementName: this.currentUserId,
        accountIdSelectVisible: false,
        requirementNameSelectVisible: false
      })
    },
    returnParams(){
      return  this.moneyForm.request.map(item=>{
        return {
          platformId:item.platformId,
          accountName:item.name,
          customerFullName:this.customerList.find(it=>it.platformId === item.platformId)['customerFullName'],
          platform:item.platform,
          accountOperator:item.operatorName,
          requirementName:item.operator,
          amount:item.amount,
          level:item.level,
          limits:item.limits
        }
       })
      // console.log(test)
    },
    async saveRequest() {
      let paramsArr=[]
      paramsArr = this.returnParams()
      // this.moneyForm.request(item=>item.level=1)
      // if (this.moneyForm.request.length === 0) return
      if(paramsArr.some(item=>{
       return item.amount ==undefined
      })) return this.$message.warning('请完善表单')
      if(paramsArr.some(item=>{
        return item.level ==undefined
      })) return this.$message.warning('请完善表单')
      if(paramsArr.some(item=>{
        return item.amount <10
      })) return this.$message.warning('充值金额不得低于10')
      // this.btnLoading = true
      // console.log('this.returnParams()',this.returnParams())
      const {data: res} = await saveRequirementByBatch(paramsArr).finally(() => {
        this.btnLoading = false
        this.selectionList=[]
      })
      // console.log(res)
      if (res.code !== 200) return
      this.$message.success('保存成功')
      this.closeMoneyForm()
      this.getAccountList()
    },
    //excel导出
    async excelExport() {

      const res = await excelExport({sortList: JSON.stringify(this.sortList)},
        this.query)
      let filename = window.decodeURI(res.headers['content-disposition'].split('=')[1])
      let url = window.URL.createObjectURL(new Blob([res.data]))
      let link = document.createElement("a")
      link.style.display = "none"
      link.href = url
      link.download = filename
      document.body.appendChild(link)
      link.click()
    },
    async getOfferList() {
      const {data: res} = await getOffer()
      this.offerList = res.data.map(item => {
        return {
          value: item.key,
          label: item.name
        }
      })
    },
    // 获取运营人
    async getOperatorList() {
      const {data: res} = await getOperator()
      this.operatorList = res.data.map(item => {
        return {
          value: item.key,
          label: item.name
        }
      })
    },
    getRowClassName({row}) {
      if (row.id == this.currOpRowId) {
        return "current-op-row";
      } else {
        return "";
      }
    },
    //媒体 logo
    platformLogo(platform) {
      return platformLogo(platform)
    },
    //钱千分位
    thousandSeparator(num) {
      return Object.assign(thousandSeparator(num))
    },
    setUpdateTime() {
      let nowDate = new Date();
      let dateStr = dateFormat(nowDate, 'yyyy-MM-dd')
      let time = ['08:30', '13:30', '18:30']
      if (checkAuditTime(time[0], time[1])) {
        this.updateTime = dateStr + " " + time[0];
      } else if (checkAuditTime(time[1], time[2])) {
        this.updateTime = dateStr + " " + time[1];
      } else {
        this.updateTime = dateStr + " " + time[2];
      }

    },
    // 排序方法
    handleSortChange(val) {
      let prop = val.prop;
      let orderBy = null;
      if (val.order === "descending") {
        orderBy = 'desc';
        //向上排序
      } else if (val.order === "ascending") {
        orderBy = 'asc';
        //不排序
      }
      if (orderBy != null) {
        this.sortList = [{name: prop, orderBy: orderBy}];
      } else {
        this.sortList = [];
      }
      this.onLoad(this.page)
    }
  }
};
</script>
<style lang="scss" scoped>
/deep/ .current-op-row {
  background-color: #f5dab1;
}

.query_select {
  margin-left: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.query_select div {
  color: #999999;
  margin-right: 250px;
  float: right;
}

.update_time {
  color: #999999;
  font-size: 14px;
  margin-right: 10px;
}

.popover_pane {
  display: flex;
  flex-direction: column;

  div {
    margin-left: 5px;


  }

  span {
    margin-left: 10px;
    font-size: 14px;
  }
}

.text-link {
  text-decoration: underline;
}
</style>
